﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Painter3D.RenderSys
{
    /// <summary>
    /// 通过标识渲染层，控制渲染的层次
    /// </summary>
    public struct RenderLayer
    {
        /// <summary>
        /// 使用bit保存层信息
        /// </summary>
        private uint layer;

        /// <summary>
        /// 存储渲染层索引和名字的配对关系
        /// </summary>
        private static Dictionary<string, uint> RenderLayerDic = new Dictionary<string, uint>() { };

        public RenderLayer(params string[] layerNames)
        {
            layer = 0;
            SetLayer(layerNames);
        }

        //public RenderLayer(string layerName)
        //{
        //    layer = 0;
        //    SetLayer(layerName);
        //}

        public bool InMask(uint mask)
        {
            return (mask & layer) != 0;
        }

        static public uint GetMask(params string[] layerNames)
        {
            uint mask = 0;
            foreach (string layerName in layerNames)
            {
                if (RenderLayerDic.ContainsKey(layerName))
                {
                    mask |= RenderLayerDic[layerName];
                }
            }
            return mask;
        }

        public void SetLayer(params string[] layerNames)
        {
            layer = 0;
            foreach (var layerName in layerNames)
            {
                if (!RenderLayerDic.ContainsKey(layerName))
                {
                    if (RenderLayerDic.Count > sizeof(int) * 8)
                        throw new Exception("无法在定义更多的层级");
                    RenderLayerDic.Add(layerName, ((uint)1 << RenderLayerDic.Count));
                }
                layer |= RenderLayerDic[layerName];
            }
        }

        public override string ToString()
        {
            long bitNum = long.Parse(Convert.ToString(layer, 2));
            if (bitNum < 1111111111111111)
            {
                return String.Format("{0:D16}", bitNum);
            }
            else
            {
                return String.Format("{0:D32}", bitNum);
            }

        }

        //public void SetLayer(string layerName)
        //{
        //    layer = 0;
        //    if (!RenderLayerDic.ContainsKey(layerName))
        //    {
        //        if (RenderLayerDic.Count > sizeof(int) * 8)
        //            throw new Exception("无法在定义更多的层级");
        //        RenderLayerDic.Add(layerName, ((uint)1 << RenderLayerDic.Count));
        //    }
        //    layer = RenderLayerDic[layerName];
        //}

    }
}
